package cn.wolfcode.shop.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;

import cn.wolfcode.shop.domain.Invoice;
import cn.wolfcode.shop.domain.OrderInfo;
import cn.wolfcode.shop.domain.OrderProduct;
import cn.wolfcode.shop.domain.OrderProductProperty;
import cn.wolfcode.shop.domain.Product;
import cn.wolfcode.shop.domain.ProductSku;
import cn.wolfcode.shop.domain.UserAddress;
import cn.wolfcode.shop.mapper.InvoiceMapper;
import cn.wolfcode.shop.mapper.OrderInfoMapper;
import cn.wolfcode.shop.mapper.OrderProductMapper;
import cn.wolfcode.shop.mapper.OrderProductPropertyMapper;
import cn.wolfcode.shop.message.CreateActionProducer;
import cn.wolfcode.shop.qo.OrderQueryObject;
import cn.wolfcode.shop.qo.PageResult;
import cn.wolfcode.shop.service.IOrderActionService;
import cn.wolfcode.shop.service.IOrderInfoService;
import cn.wolfcode.shop.service.IProductService;
import cn.wolfcode.shop.service.IProductSkuService;
import cn.wolfcode.shop.service.IUserAddressService;
import cn.wolfcode.shop.util.IdGenerateUtil;
import cn.wolfcode.shop.util.RedisConstance;
import cn.wolfcode.shop.vo.ActionVo;
import cn.wolfcode.shop.vo.CarVo;
import cn.wolfcode.shop.vo.OrderStatusChangeVo;
import cn.wolfcode.shop.vo.OrderVo;

@Service
@Transactional
public class OrderInfoServiceImpl implements IOrderInfoService {

	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Reference
	private IUserAddressService userAddressService;
	@Reference
	private IProductSkuService productSkuService;
	@Reference
	private IProductService productService;
	@Autowired
	private OrderProductPropertyMapper orderProductPropertyMapper;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private InvoiceMapper invoiceMapper;
	@Autowired
	IOrderActionService orderActionService;
	@Autowired
	private CreateActionProducer createActionProducer;

	@Override
	public void createOrder(OrderVo orderVo) {
		// 创建订单对象,设置用户id
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setUserId(orderVo.getUserLogin().getId());
		// 生成订单编号
		long orderSn = IdGenerateUtil.get().nextId();
		orderInfo.setOrderSn(orderSn + "");
		// 通过用户收获地址id获取用户收获地址的对象,并设置的订单信息中
		UserAddress userAddress = userAddressService.getAddressById(orderVo.getUserAddressId());
		orderInfo.setAddress(userAddress.getAddress());
		orderInfo.setCity(userAddress.getCity());
		orderInfo.setConsignee(userAddress.getConsignee());
		orderInfo.setCountry(userAddress.getCountry());
		orderInfo.setDistrict(userAddress.getDistrict());
		orderInfo.setPhone(userAddress.getPhone());
		orderInfo.setProvince(userAddress.getProvince());
		orderInfo.setZipcode(userAddress.getZipcode());
		// 设置订单的其他信息,比如订单状态,收货状态,物流状态,下单时间等
		orderInfo.setOrderStatus(new Byte("0"));
		orderInfo.setPayStatus(new Byte("0"));
		orderInfo.setFlowStatus(new Byte("0"));
		orderInfo.setOrderTime(new Date());
		orderInfo.setPayType(orderVo.getPay().getPayType());
		// 设置订单总金额
		BigDecimal orderAmount = BigDecimal.ZERO;
		orderInfo.setOrderAmount(orderAmount);
		// 插入订单
		orderInfoMapper.insert(orderInfo);
		// 获取购物车列表,进行遍历,并生成订单商品的明细
		for (CarVo carVo : orderVo.getCarList()) {
			// car的信息转移到订单商品的明细中
			OrderProduct orderProduct = new OrderProduct();
			orderProduct.setOrderId(orderInfo.getId());
			orderProduct.setProductNumber(carVo.getNumber());
			orderProduct.setSkuId(carVo.getSkuId());
			// 通过skuId获取sku对象,并设置价格
			ProductSku productSku = productSkuService.getById(carVo.getSkuId());
			orderProduct.setProductPrice(productSku.getPrice());
			// 计算订单明细中的商品小计
			orderProduct.setTotalPrice(orderProduct.getProductPrice().multiply(new BigDecimal(carVo.getNumber())));
			// 商品订单总额
			orderAmount = orderAmount.add(orderProduct.getTotalPrice());
			// 设置商品相关的信息
			Product product = productService.getProductById(productSku.getProductId());
			orderProduct.setProductImg(product.getImage());
			orderProduct.setProductName(product.getName());
			// 插入订单明细
			orderProductMapper.insert(orderProduct);
			productSku.getProductSkuPropertyList().forEach(productSkuProperty -> {
				OrderProductProperty orderProductProperty = new OrderProductProperty();
				orderProductProperty.setOrderProductId(orderProduct.getId());
				orderProductProperty.setName(productSkuProperty.getSkuProperty().getName());
				orderProductProperty.setValue(productSkuProperty.getValue());
				orderProductPropertyMapper.insert(orderProductProperty);
			});
			// 判断redis中有无该购物车数据,如果有需要删除
			String carKey = RedisConstance.CAR_KEY.replace("USERID", orderVo.getUserLogin().getId() + "")
					.replace("PRODUCTID", product.getId() + "").replace("SKUID", productSku.getId() + "");
			redisTemplate.delete(carKey);
		}
		// 从新设置订单总额
		orderInfo.setOrderAmount(orderAmount);
		// 更新订单
		orderInfoMapper.updateByPrimaryKey(orderInfo);
		// 判断是否需要开发票,如果要的话,需要对应订单,插入发票信息
		Invoice invoice = orderVo.getInvoice();
		if (invoice != null) {
			invoice.setUserId(orderVo.getUserLogin().getId());
			invoice.setOrderId(orderInfo.getId());
			invoiceMapper.insert(invoice);
		}
		// 新增一条订单修改日志
		OrderStatusChangeVo vo = new OrderStatusChangeVo();
		vo.setNote("订单生产");
		vo.setPlace("后台");
		vo.setUserName(orderVo.getUserLogin().getUserName());
		//
		//		orderActionService.addAction(orderInfo, vo);
		ActionVo actionVo = new ActionVo();
		actionVo.setOrderInfo(orderInfo);
		actionVo.setOrderStatusChangeVo(vo);
		// 队列方式生成日志
		createActionProducer.sendMessage(JSON.toJSONString(actionVo));

	}

	@Override
	public PageResult query(OrderQueryObject qo) {
		int count = orderInfoMapper.queryCount(qo);
		if (count == 0) {
			return PageResult.empty();
		}
		List<OrderInfo> orderInfoList = orderInfoMapper.queryList(qo);

		return new PageResult(orderInfoList, count, qo.getCurrentPage(), qo.getPageSize());
	}

	@Override
	public OrderInfo getById(Long id) {
		return orderInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public void changeOrderStatus(OrderStatusChangeVo vo) {
		// 根据前台上传的类型,判断是什么操作,分别对状态进行设置
		OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(vo.getOrderId());
		switch (vo.getChangeType()) {
		case 1:
			// 如果是1的话,需要将订单状态改为1
			orderInfo.setOrderStatus(new Byte("1"));
			break;
		case 2:
			// 如果是2的话,把订单物流状态改成4
			orderInfo.setFlowStatus(new Byte("1"));
			break;
		case 3:
			// 如果是3,将物流状态改为4
			orderInfo.setFlowStatus(new Byte("4"));
			break;
		case 4:
			// 如果是4,不需要修改
			break;
		case 5:
			// 如果是5,则需要修改订单状态为2,物流状态为2
			orderInfo.setOrderStatus(new Byte("2"));
			orderInfo.setFlowStatus(new Byte("2"));
		default:
			break;
		}
		// 更新订单
		orderInfoMapper.updateByPrimaryKey(orderInfo);
		// 新增一条订单的操作日志,
		//		orderActionService.addAction(orderInfo, vo);
		ActionVo actionVo = new ActionVo();
		actionVo.setOrderInfo(orderInfo);
		actionVo.setOrderStatusChangeVo(vo);
		createActionProducer.sendMessage(JSON.toJSONString(actionVo));

	}

}
